<template>
  <div class="w-full border border-[#dcdfe6]">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="valueHtml"
      class="w-full"
      :style="{ height: height + 'px' }"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { computed, onBeforeUnmount, shallowRef } from "vue";
import { IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { message } from "@/utils/message";

interface Props {
  modelValue: string | undefined;
  placeholder?: string;
  mode?: string;
  // 编辑器的高度
  height?: number;
  // 排除工具栏
  excludeKeys?: Array<string>;
}
interface EmitEvent {
  (e: "update:modelValue", params: string): void;
}
const props = withDefaults(defineProps<Props>(), {
  mode: "simple",
  height: 450,
  excludeKeys: () => ["fullScreen", "codeBlock", "uploadVideo"]
});
const emit = defineEmits<EmitEvent>();
const valueHtml = computed({
  get() {
    return props.modelValue;
  },
  set(value: string) {
    emit("update:modelValue", value);
  }
});
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: props.excludeKeys
};

const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload(file: File) {
        if (file.size > 3 * 1024 * 1024) {
          message("上传的图片不能超过3mb", { type: "warning" });
        }
      },
      base64LimitSize: 3 * 1024 * 1024
    }
  }
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const { value } = editorRef;
  if (value === null) return;
  value.destroy();
});
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>
